package com.tjmc.nsia.core.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.tjmc.nsia.core.dao.entity.NsiaChat;
import com.tjmc.nsia.core.service.NsiaInteractionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author Luc
 * @version 1.0
 * @date 2024-06-29 9:54
 */
@Component
@ServerEndpoint("/wsChat/{userId}")  // 接口路径 ws://localhost:XXXX/webSocket/userId;
public class WebSocketChatServer {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketChatServer.class);

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    /**
     * 用户ID
     */
    private String userId;

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    //虽然@Component默认是单例模式的，但springboot还是会为每个websocket连接初始化一个bean，所以可以用一个静态set保存起来。
    //  注：底下WebSocket是当前类名
    private static CopyOnWriteArraySet<WebSocketChatServer> webSocketServers = new CopyOnWriteArraySet<>();
    // 用来存在线连接用户信息
    private static ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();


    /**
     * 链接成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        try {
            this.session = session;
            this.userId = URLDecoder.decode(userId, "UTF-8");
            webSocketServers.add(this);
            sessionPool.put(userId, session);
            logger.info("【websocket消息】有新的连接，连接为：" + this.userId + ", 总数为:" + webSocketServers.size());
            this.sendOneMessage(this.userId, JSON.toJSONString(new HashMap<String, String>(){{
                put("type", "openCompleted");
            }}));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 链接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        try {
            webSocketServers.remove(this);
            sessionPool.remove(this.userId);
            logger.info("【websocket消息】连接断开，总数为:" + webSocketServers.size());
        } catch (Exception e) {
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message) throws UnsupportedEncodingException {
        logger.info("【websocket消息】收到客户端消息: " + message);
        String decodedString = URLDecoder.decode(message, "UTF-8");
        JSONObject response = JSON.parseObject(decodedString);
        logger.info("【websocket消息】收到客户端消息, 解码后: " + response);
        if (!Objects.isNull(response)) {
            String type = response.getString("type");
            if (StringUtils.hasText(type)) {
                String userId = response.getString("sessionId");
                if("ping".equals(type) && StringUtils.hasText(userId)) {
                    this.sendOneMessage(userId, JSON.toJSONString(new HashMap<String, String>(){{
                        put("type", "pong");
                    }}));
                } else if("webSocketResponse".equals(type)) {
                    NsiaChat nsiaChat = response.getObject("chat", NsiaChat.class);
                    NsiaInteractionService nsiaInteractionService = SpringUtils.getBean(NsiaInteractionService.class);
                    nsiaInteractionService.webSocketResponse(nsiaChat, nsiaChat.getChatId());
                }
            }
        }
    }

    @OnMessage
    public void onMessage(byte[] message) throws IOException {
        byte[] data = Arrays.copyOfRange(message, 0, message.length);
        String msg = new String(data, "UTF-8");
        logger.info("onMessage byte：" + msg);
        this.onMessage(msg);
    }

    /**
     * 发送错误时的处理
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("用户错误,原因:" + error.getMessage());
        error.printStackTrace();
    }


    // 此为广播消息
    public void sendAllMessage(String message) {
        logger.info("【websocket消息】广播消息:" + message);
        for (WebSocketChatServer webSocketServer : webSocketServers) {
            try {

                if (webSocketServer.session.isOpen()) {
                    webSocketServer.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息
    public void sendOneMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            try {
                logger.info("【websocket消息】 单点消息:" + message);
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMessageAsynchronously(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            CompletableFuture.runAsync(() -> {
                synchronized (session) {
                    try {
                        logger.info("【websocket消息】 异步单点消息:" + message);
                        session.getBasicRemote().sendText(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }

    // 此为单点消息(多人)
    public void sendMoreMessage(String[] userIds, String message) {
        for (String userId : userIds) {
            Session session = sessionPool.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    logger.info("【websocket消息】 单点消息:" + message);
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
